package cn.dujc.superkid.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.TextColorBuilder;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.adapter.ExamAnswerAdapter;
import cn.dujc.superkid.adapter.ExamMsgAdapter;
import cn.dujc.superkid.adapter.UnitTestAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.ExamineListEntity;
import cn.dujc.superkid.bean.ExaminePageResult;
import cn.dujc.superkid.bean.ExamineResultsResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.ResultsEntity;
import cn.dujc.superkid.bean.ScoreStatisticsEntity;
import cn.dujc.superkid.utils.Preferences;

public class ExamAnswerActivity extends BaseActivity implements UnitTestAdapter.OnItemViewClickListener, TextWatcher, View.OnClickListener {
    public static final String EXTRA_MYTEST = "EXTRA_COURSE";
    private String examineid;
    private List<ExaminePageResult.ExListBean> followList = new ArrayList<>();
    private ExamAnswerAdapter examAnswerAdapter;
    private Chronometer chronometer;
    private TextView tv_title;
    private RecyclerView recyclerView;
    private Button bt_tijiao;
    private LinearLayout l_liuyan;
    ExamMsgAdapter msgAdapter;
    private RecyclerView msgRecycler;
    private View liuyan_group;
    private EditText liuyan_edit;
    private TextView liuyan_submit;

    @Override
    public void initBasic(Bundle savedInstanceState) {
        setTitle("考试");
        initView();
        loadData(1);
    }

    private void initView() {
        liuyan_submit = findViewById(R.id.liuyan_submit);
        liuyan_submit.setOnClickListener(this);
        liuyan_edit = findViewById(R.id.liuyan_edit);
        liuyan_edit.addTextChangedListener(this);
        liuyan_group = findViewById(R.id.liuyan_group);
        msgRecycler=findViewById(R.id.ex_msg_recy);
        msgRecycler.setNestedScrollingEnabled(false);
        msgRecycler.setLayoutManager(new LinearLayoutManager(this));
        msgAdapter=new ExamMsgAdapter(this);
        msgRecycler.setAdapter(msgAdapter);
        recyclerView = findViewById(R.id.ex_recy);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        examAnswerAdapter = new ExamAnswerAdapter(this);
        examAnswerAdapter.setOnItemViewClickListener(this);
        recyclerView.setAdapter(examAnswerAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        tv_title = findViewById(R.id.tv_title);
        bt_tijiao = findViewById(R.id.bt_tijiao);
        l_liuyan = findViewById(R.id.l_liuyan);
        l_liuyan.setOnClickListener(this);
        chronometer = findViewById(R.id.chronometer);
        chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 / 60);
        chronometer.setFormat("0" + String.valueOf(hour) + ":%s");
        bt_tijiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitTest();
            }
        });
    }

    private void submitTest() {
        for (int i = 0; i < examAnswerAdapter.getList().size(); i++) { //校验是否有题没填写答案
            if (TextUtils.isEmpty(examAnswerAdapter.getList().get(i).getValue())) {
                ToastUtil.showToast(mActivity, "第" + (i + 1) + "题没答");
                return;
            }
        }
        requestSubmit();
    }
    public void requestSubmit(){
        if (!Preferences.isLogin(this)) {
            starter().go(LoginActivity.class);
        } else {
            final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
            HttpHelper.getExamineOnline().examineResults(QMap.build()
                    .put("user_id", loginResult.getUid())
                    .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                    .put("logincode", loginResult.getLogincode())
                    .put("examine_id", examineid)//试卷id
                    .put("answer",examAnswerAdapter.getValue())
                    .put("when",chronometer.getText())
                    .create()).enqueue(new ResultCallBack<Result<ExamineResultsResult>>(mActivity) {
                @Override
                public void onSuccessCallback(int code, Result<ExamineResultsResult> body) {
                    ArrayList<ResultsEntity> list = (ArrayList<ResultsEntity>) body.getData().getResults();
                    ArrayList<ScoreStatisticsEntity> list1 = (ArrayList<ScoreStatisticsEntity>) body.getData().getScore_statistics();
                    ArrayList<ExamineListEntity> testList=new ArrayList<>();
                    ArrayList<ExaminePageResult.ExListBean>datas= (ArrayList<ExaminePageResult.ExListBean>) examAnswerAdapter.getList();
                    for (int i=0;i<datas.size();i++){
                        ExaminePageResult.ExListBean d=datas.get(i);
                        ExamineListEntity examineListEntity=new ExamineListEntity();
                        examineListEntity.setCorrect_answer(d.getCorrect_answer());
                        examineListEntity.setExercises_answer(d.getExercises_answer_list());
                        examineListEntity.setExercises_answer_list(d.getExercises_answer_list());
                        examineListEntity.setId(d.getId());
                        examineListEntity.setProblem_title(d.getProblem_title());
                        examineListEntity.setProblem_type(d.getProblem_type());
                        testList.add(examineListEntity);
                    }
                    starter().with("unitResult", list)
                            .with("num", body.getData().getPage_info().getNum())
                            .with("first_score", "0")
                            .with("total_score", "0")
                            .with("title", body.getData().getPage_info().getExamine_title())
                            .with("statistics", list1)
                            .with("testList", testList)
                            .go(CupUnitTestResultActivity.class);
                    finish();
                }
            });
        }
    }
    @Override
    public int getViewId() {
        examineid = extras().get(EXTRA_MYTEST);
        return R.layout.activity_examanswer;
    }


    private void loadData(final int type) {
        if (!Preferences.isLogin(this)) {
            starter().go(LoginActivity.class);
        } else {
            final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
            HttpHelper.getExamineOnline().examinePage(QMap.build()
                    .put("user_id", loginResult.getUid())
                    .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                    .put("logincode", loginResult.getLogincode())
                    .put("examine_id", examineid)//试卷id
                    .create()).enqueue(new ResultCallBack<Result<ExaminePageResult>>(mActivity) {
                @Override
                public void onSuccessCallback(int code, Result<ExaminePageResult> body) {
                    if (body != null) {
                        final ExaminePageResult data = body.getData();
                        if (data != null) {
                            int color = ContextCompat.getColor(mActivity, R.color.orange);
                            tv_title.setText(new TextColorBuilder()
                                    .addTextPart("共有")
                                    .addTextPart(color, data.getQuestions_number())
                                    .addTextPart("道题目，考试时间为")
                                    .addTextPart(color, data.getEx_usedtime())
                                    .addTextPart("分钟，共计")
                                    .addTextPart(color, "100")
                                    .addTextPart("分")
                                    .build());
                            final List<ExaminePageResult.ExListBean> exList = data.getEx_list();
                            if(type==1){
                            examAnswerAdapter.setList(exList);
                            }
                            msgAdapter.setDatas(body.getData().getMessage_list());

                        }
                        chronometer.start();
                    }
                }
            });
        }
    }

    //加入到好题本
    public void addGoodQuestion(int pos) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getCourse().videoGoodQuestion(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("exercises_id", examAnswerAdapter.getList().get(pos).getId())
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 1)
                .create()).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                ToastUtil.showToast(mActivity, body.getMsg());
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                if(code==400){
                    ToastUtil.showToast(mActivity, msg);
                }else{
                    ToastUtil.showToast(mActivity, "未能读取数据，因为它的格式不正确");
                }
            }
        });
    }

    @Override
    public void onItemViewClick(View v, int pos) {
        switch (v.getId()) {
            case R.id.item_exercises_add: //加入好题本
                addGoodQuestion(pos);
                break;
            case R.id.exercises_jiexi://查看解析
                Intent intent = new Intent(this, AnalysisActivity.class);
                intent.putExtra("title", examAnswerAdapter.getList().get(pos).getProblem_title());
                switch (examAnswerAdapter.getList().get(pos).getProblem_type()){
                    case "1":
                        String value=examAnswerAdapter.getList().get(pos).getCorrect_answer().get(0);
                        String[] vs={"A","B","C","D",};
                        intent.putExtra("content","正确答案为："+vs[Integer.parseInt(value)-1]);
                        break;
                    case "2":
                        break;
                    case "3":
                        String value1=examAnswerAdapter.getList().get(pos).getCorrect_answer().get(0);
                        intent.putExtra("content","正确答案为："+value1);
                        break;

                }
                startActivity(intent);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            liuyan_submit.setTextColor(Color.parseColor("#888888"));
        } else {
            liuyan_submit.setTextColor(Color.parseColor("#222222"));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==RESULT_OK){
            loadData(0);
        }
    }

    @Override
    public void onClick(View v) {
        if(v==l_liuyan){
//            liuyan_group.setVisibility(View.VISIBLE);
//            liuyan_edit.setFocusable(true);
//            liuyan_edit.setFocusableInTouchMode(true);
//            liuyan_edit.requestFocus();
//            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.showSoftInput(liuyan_edit, InputMethodManager.SHOW_FORCED);
          Intent intent =new Intent(this,LeavingActivity.class);
          intent.putExtra("type","2");
          intent.putExtra("examine_id",examineid);
          startActivityForResult(intent,1);
        }else{
            submitTest();
        }
    }
}
